package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.pojo.LoginDto;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LoginService loginService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //发送短信验证码
    @PostMapping("/validateCode/send4Login.do")
    public Result sendLogin(String telephone){
        String code = ValidateCodeUtils.generateValidateCode4String(6);

        //SendSms.sendMsg(telephone,code);
        System.out.println("验证码:"+code);

//        HttpSession session = request.getSession();
//        session.setAttribute(telephone,code);
        redisTemplate.opsForValue().set(telephone,code);
        redisTemplate.expire(telephone,60, TimeUnit.SECONDS);

        return new Result(true,"短信发送成功");
    }
    //验证码登录
    @PostMapping("/member/login.do")
    public Result login(@RequestBody LoginDto loginDto){
        if (loginDto == null){
            return new Result(false,"参数错误");
        }
        //从Session中获取到手机号对应的正确的验证码
        HttpSession session = request.getSession();
        //String code = (String) session.getAttribute(loginDto.getTelephone());
        String code = redisTemplate.opsForValue().get(loginDto.getTelephone());
        // 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if (code == null){
            return new Result(false,"请先获得验证码");
        }
        if (!code.equals(loginDto.getValidateCode())){
            return new Result(false,"验证码错误");
        }
        //如果比对成功, 需要根据手机号查询当前用户
        Member member = loginService.findByPhone(loginDto.getTelephone());
        if (member == null){
            //如果用户不存在, 则自动注册一个新用户
            Member memberNew = loginService.add(loginDto.getTelephone());
            session.setAttribute("memberId",memberNew.getId());
            return new Result(true,"注册成功");
        }
        //将登录用户的ID存储Session中
        session.setAttribute("memberId",member.getId());
        return new Result(true,"登录成功");
    }
    @PostMapping("/validateCode/send4Order.do")
    public Result send4Order(String telephone){

        String code = ValidateCodeUtils.generateValidateCode4String(6);

        System.out.println("验证码:"+code);

        HttpSession session = request.getSession();
        session.setAttribute(telephone,code);

        return new Result(true,"发送成功");
    }

}
